import Vue from "vue";
import Router from "vue-router";
import { getRouters } from "@/api/routers";
import { resolve } from "path";
import { componentMap } from "@/config/routers";
import { getLang } from "@/utils/lang";

Vue.use(Router);

/**
 * 递归所有路由项，将component中的字符串，通过映射表componentMap，转为对应的组件module
 * @param {*} item
 */
const getComponent = item => {
  let componentUrl = componentMap[item.component];
  const componentVal = resolve => {
    require(["@/pages" + componentUrl], resolve);
  };
  item.component = componentVal;

  if (item.children) {
    item.children.forEach(child => {
      getComponent(child);
    });
  }
};

/**
 * 判断网站的语言
 */
import store from "@/store/index";
let lang = getLang();
if (lang == "en") {
  store.dispatch("switchEnglishRoute");
} else {
  store.dispatch("switchChineseRoute");
}

/**
 * 创建路由，并传入本地路由
 */
let localRoutes = store.state.router.localRoutes;
localRoutes.forEach(route => {
  getComponent(route);
});
const router = new Router({
  // mode: "history",
  routes: localRoutes,
  scrollBehavior(to, from, savedPosition) {
    return {
      x: 0,
      y: 0
    };
  }
});

/**
 * 通过接口获取后台配置的路由
 */
store.dispatch("GetRemoteRoutes").then(res => {
  let remoteRoutes = res;
  remoteRoutes.forEach(ele => {
    // 1.将每个路由中的component中的字符串，通过映射表componentMap，转为对应的组件module
    getComponent(ele);

    // 2.为一级路由配redirect,指向其children的第一个元素
    if (ele.children) {
      ele.redirect = `${ele.path}/${ele.children[0].path}`;
    }
  });
  router.addRoutes(remoteRoutes); // 3.向路由对象中添加处理好的远程路由配置项。
  store.dispatch("remoteRoutesAdded");
});

/**
 * 路由守护器，页面跳转前执行
 */
import { needLogin } from "@/config/needLoginList";
import { getList } from "@/api/list";
const wapRoot = "http://www.csm.hn.cn/cbo/page/"; // 设置手机网站域名
let client = false; // 客户端类型：false为未知， "web" 为PC, "wap"  为手机移动端。

router.beforeResolve((to, from, next) => {
  const wapRouterMap = [
    {
      title: "三级文章详情页",
      reg: /\/[a-z]+\/[a-z]+-list-[0-9]+\/detail\/[0-9]+/,
      wapUrl: "commentPage.html",
      params: {
        id: to.params.id,
        type: 3
      }
    },
    {
      title: "典藏概况详情",
      reg: /\/collection\/state\/detail\/[0-9]+/,
      wapUrl: "collection_goods.html",
      params: {
        id: to.params.id,
        type: 1,
        cltypeId: to.query.sid
      }
    },
    {
      title: "活动预约详情",
      reg: /\/study\/appointment\/detail\/[0-9]+/,
      wapUrl: "active_detail.html",
      params: {
        id: to.params.id,
        type: 8
      }
    },
    {
      title: "学习资讯页面",
      reg: /\/study\/news\/detail\/[0-9]+/,
      wapUrl: "commentPage.html",
      params: {
        id: to.params.id,
        apiType: "1"
      }
    },
    {
      title: "文创商品详情",
      reg: /\/winchance\/craft\/detail\/[0-9]+/,
      wapUrl: "info_goodsdetails.html",
      params: {
        id: to.params.id,
        type: 2
      }
    },
    {
      title: "众筹活动详情",
      reg: /\/winchance\/crowdfunding\/detail\/[0-9]+/,
      wapUrl: "info_idea.html",
      params: {
        id: to.params.id,
        type: 6
      }
    },
    {
      title: "投票活动详情",
      reg: /\/winchance\/vote\/detail\/[0-9]+/,
      wapUrl: "info_vote.html",
      params: {
        id: to.params.id,
        type: 7
      }
    },
    {
      title: "基本陈列、特别展览、展览回顾详情页",
      reg: /#\/specexhibition\/[0-9]+\/.*/,
      wapUrl: "home_cldetial.html",
      params: {
        id: "",
        cldetial_id: to.params.id
      }
    },
    {
      title: "default",
      reg: /.*/,
      wapUrl: "index.html",
      params: {
        id: "0"
      }
    }
  ];
  const secondary_detail = {
    title: "二级文章详情页",
    reg: /\/[a-z]+\/[a-z]+-detail-[0-9]+/,
    wapUrl: "commentPage.html",
    params: {
      type: 3
    }
  };

  // 需要登陆的页面，在跳转前先判断是否登陆
  let need = needLogin.includes(to.name);
  let isLogin = store.getters.userId ? true : false;
  if (need && !isLogin) {
    if (!from.name) {
      next("/home");
    } else {
      store.dispatch("ToggleNeedLogin", true);
      next(false);
      return false;
    }
  }

  // 判断用户端是否为手机端，并跳转到相应页面
  function isGotoWap(param) {
    if (client) {
      if (client === "wap") {
        let path = window.location.hash.toLowerCase();

        if (path.indexOf("landmark/web/") != -1) {
          // 判断如果是长沙地标则不跳转
          return false;
        }

        // 如果是客户端为移动端，则执行以下代码

        // let path = window.location.hash.toLowerCase();

        if (secondary_detail.reg.test(path)) {
          // 如果是二级详情页，则先通过列表接口获取文章列表，将第一条数据的id带到手机网站
          let listId = to.path.split("-").pop();
          getList(listId).then(res => {
            secondary_detail.params.id = res.data.recordsList[0].id;
            gotoWap(secondary_detail.wapUrl, secondary_detail.params);
            return false;
          });
        } else {
          for (let i = 0; i < wapRouterMap.length; i++) {
            if (wapRouterMap[i].reg.test(path)) {
              let id = path.split("/").pop();
              wapRouterMap[i].params.id = id;
              gotoWap(wapRouterMap[i].wapUrl, wapRouterMap[i].params);
              return false;
            }
          }
        }
      }
    } else {
      // 判断是否为移动端设备，并未client变量赋值
      let sUserAgent = navigator.userAgent.toLowerCase();
      let bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
      let bIsIphone = sUserAgent.match(/iphone os/i) == "iphone os";
      let bIsMidp = sUserAgent.match(/midp/i) == "midp";
      let bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
      let bIsUc = sUserAgent.match(/ucweb/i) == "web";
      let bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
      let bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
      let bIsAndroid = sUserAgent.match(/android/i) == "android";
      if (
        bIsIphone ||
        bIsMidp ||
        bIsUc7 ||
        bIsUc ||
        bIsCE ||
        bIsWM ||
        bIsAndroid
      ) {
        client = "wap";
      } else {
        client = "web";
      }
      isGotoWap();
    }
  }
  isGotoWap();
  next();
});

/**
 * 跳转至目标页面
 * @param {String} wapUrl 跳转路径
 * @param {Obj} params 所携带参数
 */
function gotoWap(wapUrl, params) {
  let query = `?`;
  if (params) {
    for (let key in params) {
      query += `${key}=${params[key]}&`;
    }
  }
  let url = `${wapRoot}${wapUrl}${query}`;
  window.location.href = url;
}

export default router;
